﻿<%@ WebHandler Language="C#" Class="IncomeDetailsOwner" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;

public class IncomeDetailsOwner : AjaxHandlerBase
{
    public IncomeDetailsOwner()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_IncomeDetailsOwner_Export);
        htTypePermit.Add("exportall", Constants.Permit_IncomeDetailsOwner_Export);
    }

    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                case "getlist":
                    GetList(context);
                    break;
                case "exportall":
                    ExportAll(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void ExportAll(HttpContext context)
    {
        System.Text.StringBuilder sbWhere = new System.Text.StringBuilder();

        sbWhere.Append(" (1=1) and status=1 ");

        //关键字
        if (!string.IsNullOrEmpty(context.Request["Keyword"]))
            sbWhere.AppendFormat(" and (ContractCode like '%{0}%' or HouseAddress like '%{0}%')", context.Request["Keyword"]);
        //收付款日期
        if (!string.IsNullOrEmpty(context.Request["StartTime"]))
            sbWhere.AppendFormat(" and PayDate>='{0}' ", context.Request["StartTime"]);
        if (!string.IsNullOrEmpty(context.Request["EndTime"]))
            sbWhere.AppendFormat(" and PayDate<='{0}' ", context.Request["EndTime"]);
        //实收归属
        if (!string.IsNullOrEmpty(context.Request["ActualDate"]))
        {
            string actualdate = "";
            string[] list = context.Request["ActualDate"].Split('-');
            actualdate = list[0] + "." + list[1].TrimStart('0');
            sbWhere.AppendFormat(" and PayArchDate='{0}' ", actualdate);
        }
        //10:点数所属，20：合同所属
        if (context.Request["type"] == "10")
        {
            //5级
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["UserId"])) ? Guid.Empty : new Guid(context.Request["UserId"]);

            if (userId != Guid.Empty)
                sbWhere.AppendFormat(" AND (PointEmpId = '{0}') ", userId);
            else if (departs != Guid.Empty)
            {
                sbWhere.AppendFormat(" and pointdepartid = '{0}'", departs);
            }
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null)
                {
                    context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, "获取商圈或分类数据丢失", ""));
                }
                sbWhere.AppendFormat(" and (pointdepartid in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
            {
                sbWhere.AppendFormat(" and (pointdepartid in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", company);
            }
            else if (city != Guid.Empty)
            {
                sbWhere.AppendFormat(" and (pointdepartid in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", city);
            }
        }
        else if (context.Request["type"] == "20")
        {
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            if (company != Guid.Empty)
            {
                sbWhere.AppendFormat(" and BargainCompanyId='{0}' ", company);
            }
            else if (city != Guid.Empty)
            {
                sbWhere.AppendFormat(" and BargainCityId='{0}' ", city);
            }
        }

        //欲选择字段列表 
        //string FieldList = "PointDepartId,business,departname,ContractCode,ContractDate,HouseAddress,PointEmp,DeparterManagerName,MangerName,RegionManagerName,MajordomoName,StanCommision,RealCommisionFinal,"
        //    + "CommisionFinal,ConsultingFinal,Point,PayMoney,ApportionRealCommisionFinal,ApportionCommisionFinal,ApportionConsultingFinal,ApportionPay,PayDate,PayArchDate,ContractArchDate,BargainCompanyName";


        //所要查询的表名
        string TableName = "v_Contract_FinanceDetailInfo";
        //排序
        string strOrderField = " PointDepartId desc";


        //排序
        if (!string.IsNullOrEmpty(context.Request["sort"]))
            strOrderField = context.Request["sort"];

        //查询语句
        System.Text.StringBuilder sbSql = new System.Text.StringBuilder();
        sbSql.Append("PointDepartId,dbo.FN_GetBussinessByDepartID(PointDepartId) as business,dbo.FN_GetDepartNameByDepartID(PointDepartId) as departname, ");
        sbSql.Append("ContractCode,REPLACE(CONVERT(Varchar(10),ContractDate,111),'/','-') As ContractDate,HouseAddress,PointEmp,DeparterManagerName,MangerName,RegionManagerName,MajordomoName,StanCommision,RealCommisionFinal,");
        sbSql.Append("CommisionFinal,ConsultingFinal,Point,PayMoney,ApportionRealCommisionFinal,ApportionCommisionFinal,ApportionConsultingFinal,ApportionPay,REPLACE(CONVERT(Varchar(10),PayDate,111),'/','-') As PayDate,");
        sbSql.Append("PayArchDate,REPLACE(CONVERT(Varchar(10),ContractArchDate,111),'/','-') As ContractArchDate,BargainCompanyName ");

        string strSql = "select " + sbSql.ToString() + " from " + TableName + " where " + sbWhere.ToString() + " order by " + strOrderField;
        string strHTML = "";
        
        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        strHTML = GetHtml(ds.Tables[0]);

        ExportByServce(context, strHTML);
    }


    private string GetHtml(System.Data.DataTable dt)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table class=\"tabsorternew table_archive\"><tr>");
        sb.Append("<th style=\"width:120px;\">商圈</th>");
        sb.Append("<th style=\"width:120px;\">门店</th>");
        sb.Append("<th style=\"width:130px;\">成交编号</th>");
        sb.Append("<th style=\"width:80px;\">成交日期</th>");
        sb.Append("<th style=\"width:270px;\">房屋地址</th>");
        sb.Append("<th style=\"width:100px;\">业务员</th>");
        sb.Append("<th style=\"width:100px;\">店长</th>");
        sb.Append("<th style=\"width:100px;\">高级经理</th>");
        sb.Append("<th style=\"width:100px;\">区域经理</th>");
        sb.Append("<th style=\"width:110px;\">总监</th>");
        sb.Append("<th style=\"width:100px;\">标准佣收</th>");
        sb.Append("<th style=\"width:100px;\">应收佣收</th>");
        sb.Append("<th style=\"width:100px;\">折佣</th>");
        sb.Append("<th style=\"width:100px;\">咨询费</th>");
        sb.Append("<th style=\"width:100px;\">点数</th>");
        sb.Append("<th style=\"width:100px;\">实收</th>");
        sb.Append("<th style=\"width:100px;\">分摊应收佣收</th>");
        sb.Append("<th style=\"width:100px;\">分摊折佣</th>");
        sb.Append("<th style=\"width:100px;\">分摊咨询费</th>");
        sb.Append("<th style=\"width:100px;\">分摊实收</th>");
        sb.Append("<th style=\"width:100px;\">收款日期</th>");
        sb.Append("<th style=\"width:100px;\">实收归属日期</th>");
        sb.Append("<th style=\"width:100px;\">业绩归属日期</th>");
        sb.Append("<th style=\"width:120px;\">合同归属公司</th></tr>");

        double point = 0.0;            //点数
        double ApportionRealCommisionFinal = 0.0;     //分摊应收佣收
        double ApportionCommisionFinal = 0.0;      //分摊折佣
        double ApportionConsultingFinal = 0.0;      //分摊咨询费
        double ApportionPay = 0.0;      //分摊实收

        foreach (System.Data.DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"business",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"departname",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ContractCode",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ContractDate",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"HouseAddress",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"PointEmp",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"DeparterManagerName",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"MangerName",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"RegionManagerName",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"MajordomoName",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"StanCommision",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"RealCommisionFinal",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"CommisionFinal",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ConsultingFinal",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"Point",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"PayMoney",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ApportionRealCommisionFinal",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ApportionCommisionFinal",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ApportionConsultingFinal",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ApportionPay",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"PayDate",""));
            sb.AppendFormat("<td>{0}.1</td>", DatasetHelper.GetValue(dr,"PayArchDate",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"ContractArchDate",""));
            sb.AppendFormat("<td>{0}</td>", DatasetHelper.GetValue(dr,"BargainCompanyName",""));
            sb.Append("</tr>");

            point += string.IsNullOrEmpty(dr["Point"].ToString()) ? 0 : double.Parse(dr["Point"].ToString());
            ApportionRealCommisionFinal += string.IsNullOrEmpty(dr["ApportionRealCommisionFinal"].ToString()) ? 0 : double.Parse(dr["ApportionRealCommisionFinal"].ToString());
            ApportionCommisionFinal += string.IsNullOrEmpty(dr["ApportionCommisionFinal"].ToString()) ? 0 : double.Parse(dr["ApportionCommisionFinal"].ToString());
            ApportionConsultingFinal += string.IsNullOrEmpty(dr["ApportionConsultingFinal"].ToString()) ? 0 : double.Parse(dr["ApportionConsultingFinal"].ToString());
            ApportionPay += string.IsNullOrEmpty(dr["ApportionPay"].ToString()) ? 0 : double.Parse(dr["ApportionPay"].ToString());

        }
        sb.AppendFormat("<tr><td>总合计</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>{0}</td><td></td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td>", point, ApportionRealCommisionFinal, ApportionCommisionFinal, ApportionConsultingFinal, ApportionPay);
        sb.Append("<td></td><td></td><td></td><td></td></tr></table>");
        
        
        return sb.ToString();
    }
    

    private void GetList(HttpContext context)
    {
        System.Text.StringBuilder sbWhere = new System.Text.StringBuilder();
        //查询条件。。
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_InComeOwner_Search_All))
        {
            sbWhere.Append(" (1=1) ");
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_InComeOwner_Search_City))
        {
            sbWhere.AppendFormat(" (pointdepartid in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", CurrentUserInfo.CityId.ToString());
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_InComeOwner_Search_Company))
        {
            sbWhere.AppendFormat(" (pointdepartid in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", CurrentUserInfo.CompanyId.ToString());
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_InComeOwner_Search_Depart))
        {
            sbWhere.Append(" (EXISTS(");
            sbWhere.AppendFormat("Select 1 from t_Business_EmpSetting M WHERE v_Contract_FinanceDetailInfo.pointdepartid=M.DepartId And M.Userid= '{0}' and SearchIncomeOwner=1", CurrentUserInfo.UserId.ToString());
            sbWhere.Append(")) ");
        }
        else
            sbWhere.AppendFormat(" (PointEmpId = '{0}') ", CurrentUserInfo.UserId);

        sbWhere.Append(" and status=1");
        
        //关键字
        if (!string.IsNullOrEmpty(context.Request["Keyword"]))
            sbWhere.AppendFormat(" and (ContractCode like '%{0}%' or HouseAddress like '%{0}%')", context.Request["Keyword"]);
        //收付款日期
        if (!string.IsNullOrEmpty(context.Request["StartTime"]))
            sbWhere.AppendFormat(" and PayDate>='{0}' ", context.Request["StartTime"]);
        if (!string.IsNullOrEmpty(context.Request["EndTime"]))
            sbWhere.AppendFormat(" and PayDate<='{0}' ", context.Request["EndTime"]);
        //实收归属
        if (!string.IsNullOrEmpty(context.Request["ActualDate"]))
        {
            string actualdate = "";
            string[] list = context.Request["ActualDate"].Split('-');
            actualdate = list[0] + "." + list[1].TrimStart('0');
            sbWhere.AppendFormat(" and PayArchDate='{0}' ", actualdate);
        }
        //10:点数所属，20：合同所属
        if (context.Request["type"] == "10")
        {
            //5级
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["UserId"])) ? Guid.Empty : new Guid(context.Request["UserId"]);

            if (userId != Guid.Empty)
                sbWhere.AppendFormat(" AND (PointEmpId = '{0}') ", userId);
            else if (departs != Guid.Empty)
            {
                sbWhere.AppendFormat(" and pointdepartid = '{0}'", departs);
            }
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null)
                {
                    context.Response.Write(retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, "获取商圈或分类数据丢失", ""));
                }
                sbWhere.AppendFormat(" and (pointdepartid in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
            {
                sbWhere.AppendFormat(" and (pointdepartid in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", company);
            }
            else if (city != Guid.Empty)
            {
                sbWhere.AppendFormat(" and (pointdepartid in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", city);
            }
        }
        else if (context.Request["type"] == "20")
        {
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            if (company != Guid.Empty)
            {
                sbWhere.AppendFormat(" and BargainCompanyId='{0}' ", company);
            }
            else if (city != Guid.Empty)
            {
                sbWhere.AppendFormat(" and BargainCityId='{0}' ", city);
            }
        }

        int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
        //页显示行数
        int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
        //欲选择字段列表 
        string FieldList = "PointDepartId,business,departname,ContractCode,ContractDate,HouseAddress,PointEmp,DeparterManagerName,MangerName,RegionManagerName,MajordomoName,StanCommision,RealCommisionFinal,"
            + "CommisionFinal,ConsultingFinal,Point,PayMoney,ApportionRealCommisionFinal,ApportionCommisionFinal,ApportionConsultingFinal,ApportionPay,PayDate,PayArchDate,ContractArchDate,BargainCompanyName";


        //所要查询的表名
        string TableName = "v_Contract_FinanceDetailInfo";
        //排序
        string strOrderField = " PointDepartId desc";
        
        
        //排序
        if (!string.IsNullOrEmpty(context.Request["sort"]))
            strOrderField=context.Request["sort"];
        
        //查询语句
        System.Text.StringBuilder sbSql = new System.Text.StringBuilder();
        sbSql.Append("PointDepartId,dbo.FN_GetBussinessByDepartID(PointDepartId) as business,dbo.FN_GetDepartNameByDepartID(PointDepartId) as departname, ");
        sbSql.Append("ContractCode,ContractDate,HouseAddress,PointEmp,DeparterManagerName,MangerName,RegionManagerName,MajordomoName,StanCommision,RealCommisionFinal,");
        sbSql.Append("CommisionFinal,ConsultingFinal,Point,PayMoney,ApportionRealCommisionFinal,ApportionCommisionFinal,ApportionConsultingFinal,ApportionPay,PayDate,");
        sbSql.Append("PayArchDate,ContractArchDate,BargainCompanyName ");


        System.Data.DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strPageIndex, strPageSize, strOrderField, TableName, sbWhere.ToString(), FieldList,sbSql.ToString(),true);

        //*************添加总合计行**************************
        string strSql = "select sum(isnull(Point,0)) as Point,sum(isnull(ApportionRealCommisionFinal,0)) as ApportionRealCommisionFinal,sum(isnull(ApportionCommisionFinal,0)) as ApportionCommisionFinal,sum(isnull(ApportionConsultingFinal,0)) as ApportionConsultingFinal,sum(isnull(ApportionPay,0)) as ApportionPay from " + TableName + " where " + sbWhere.ToString();
        System.Data.DataSet ds_count = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        System.Data.DataRow dr = ds.Tables[0].NewRow();
        dr["business"] = "总合计";
        dr["Point"] = ds_count.Tables[0].Rows[0]["Point"];
        dr["ApportionRealCommisionFinal"] = ds_count.Tables[0].Rows[0]["ApportionRealCommisionFinal"];
        dr["ApportionCommisionFinal"] = ds_count.Tables[0].Rows[0]["ApportionCommisionFinal"];
        dr["ApportionConsultingFinal"] = ds_count.Tables[0].Rows[0]["ApportionConsultingFinal"];
        dr["ApportionPay"] = ds_count.Tables[0].Rows[0]["ApportionPay"];

        ds.Tables[0].Rows.Add(dr);
        //***************************************************
        
        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }
}